package com.mall.server.service;

import com.mall.dubbo.api.*;
import com.mall.server.inerceptor.UmsAdminHolder;
import com.tanhua.model.domain.*;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminService {



    @DubboReference
    private UmsAdminApi umsAdminApi;

    @DubboReference
    private UmsAdminRoleRelationApi umsAdminRoleRelationApi;

    @DubboReference
    private UmsRoleMenuRelationApi umsRoleMenuRelationApi;

    @DubboReference
    private UmsMenuApi umsMenuApi;

    @DubboReference
    private UmsRoleApi umsRoleApi;

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public UmsAdmin login(String username, String password) {
        return umsAdminApi.findOne(username,password);
    }

    /**
     * 登录返回
     *  返回值
     *      * {
     *      *     "code":200,
     *      *     "message":"操作成功",
     *      *     "data":{
     *      *         "roles":Array[1],
     *      *         "icon":"http://macro-oss.oss-cn-shenzhen.aliyuncs.com/mall/images/20180607/timg.jpg",
     *      *         "menus":Array[23],
     *      *         "username":"admin"
     *      *     }
     *      * }
     * @return
     */
    public Map<String, Object> info() {
        HashMap<String, Object> map = new HashMap<>();

        //姓名
        String name = UmsAdminHolder.getName();
        map.put("username",name);


        //头像
        Long id = UmsAdminHolder.getId();
        UmsAdmin ums_admin =umsAdminApi.findById(id);
        map.put("icon",ums_admin.getIcon());

        //查询 role_ids   一个admin_id 对应多个role_id;
        List<UmsAdminRoleRelation> uarrs=umsAdminRoleRelationApi.findByAdminId(id);

        if (uarrs == null){
            //这边是null报个异常
        }

        List<Long> role_ids = uarrs.stream().map(uarr -> {
            Long role_id = uarr.getRoleId();
            return role_id;
        }).collect(Collectors.toList());


        //查询到所有的menu_id
        List<UmsRoleMenuRelation> urmrList =umsRoleMenuRelationApi.findByRoleid(role_ids);
        List<Long> menuIds = urmrList.stream().map(urmr -> {
            Long menu_id = urmr.getMenuId();
            return menu_id;
        }).collect(Collectors.toList());

        //根据menuIds查询到ums_menu,封装进对象进行返回
        List<UmsMenu> umsAdmins =umsMenuApi.findByIds(menuIds);
        map.put("menus",umsAdmins);

        //根据role_id 查询ums_role,并且封装对象
        List<UmsRole> ums_roles =umsRoleApi.finById(role_ids);
        List<String> umsRoleNames = ums_roles.stream().map(ums_role -> {

            return ums_role.getName();
        }).collect(Collectors.toList());
        map.put("roles",umsRoleNames);

        return map;
    }
}
